package com.pmoc.framework.core.config.driver.redis;


import com.pmoc.framework.core.annos.PmocType;
import com.pmoc.framework.core.enums.TypeEnum;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * Redis 判定条件
 *
 * @author humdeef
 * @summary Redis 判定条件
 * @since 2019-05-13 19:06
 */
public class RedisCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //获取beanfactory
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        //获取当前环境信息
        Environment environment = context.getEnvironment();

        /**
         * 两种方式来判断使用的是redis存储模式
         */
        //第一种
        String property = environment.getProperty("spring.redis.url");
        if (property != null && property.contains("redis://")) {
            return true;
        }
        //第二种
        Map<String, Object> beansWithAnnotation = beanFactory.getBeansWithAnnotation(PmocType.class);
        if (!CollectionUtils.isEmpty(beansWithAnnotation)) {
            for (Map.Entry<String, Object> entry : beansWithAnnotation.entrySet()) {
                Object value = entry.getValue();
                if (value != null) {
                    PmocType annotation = AnnotationUtils.findAnnotation(value.getClass(), PmocType.class);
                    if (annotation == null || annotation.value() == TypeEnum.REDIS) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
